import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { Zap, Timer, Target, RotateCcw } from 'lucide-react';
import { TestResult } from '../types';

interface ReactionTimeTestProps {
  onComplete: (result: TestResult) => void;
}

type TestState = 'ready' | 'waiting' | 'react' | 'too-early' | 'complete';

export function ReactionTimeTest({ onComplete }: ReactionTimeTestProps) {
  const [state, setState] = useState<TestState>('ready');
  const [currentRound, setCurrentRound] = useState(0);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [testStartTime, setTestStartTime] = useState<number>(0);
  const [countdown, setCountdown] = useState<number>(0);
  const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);

  const totalRounds = 5;
  const maxWaitTime = 5000; // 5 seconds max wait
  const minWaitTime = 1000; // 1 second min wait

  const startRound = useCallback(() => {
    // 如果是第一轮，记录测试开始时间
    if (currentRound === 0 && reactionTimes.length === 0) {
      setTestStartTime(Date.now());
    }
    
    setState('waiting');
    setCountdown(3);
    
    // Countdown
    const countdownInterval = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(countdownInterval);
          
          // Random delay before showing react screen
          const delay = minWaitTime + Math.random() * (maxWaitTime - minWaitTime);
          const timeout = setTimeout(() => {
            setStartTime(Date.now());
            setState('react');
          }, delay);
          
          setTimeoutId(timeout);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  }, [currentRound, reactionTimes.length]);

  const handleReaction = useCallback(() => {
    if (state === 'waiting') {
      setState('too-early');
      if (timeoutId) {
        clearTimeout(timeoutId);
        setTimeoutId(null);
      }
      return;
    }
    
    if (state === 'react') {
      const reactionTime = Date.now() - startTime;
      setReactionTimes(prev => [...prev, reactionTime]);
      
      if (currentRound + 1 >= totalRounds) {
        setState('complete');
      } else {
        setCurrentRound(prev => prev + 1);
        setState('ready');
      }
    }
  }, [state, startTime, currentRound, timeoutId]);

  const resetTest = () => {
    setState('ready');
    setCurrentRound(0);
    setReactionTimes([]);
    setStartTime(0);
    setTestStartTime(0);
    setCountdown(0);
    if (timeoutId) {
      clearTimeout(timeoutId);
      setTimeoutId(null);
    }
  };

  const getAverageTime = () => {
    if (reactionTimes.length === 0) return 0;
    return Math.round(reactionTimes.reduce((a, b) => a + b, 0) / reactionTimes.length);
  };

  const getScore = () => {
    const avgTime = getAverageTime();
    if (avgTime < 200) return 100;
    if (avgTime < 250) return 90;
    if (avgTime < 300) return 80;
    if (avgTime < 350) return 70;
    if (avgTime < 400) return 60;
    if (avgTime < 500) return 50;
    return 40;
  };

  const getRating = () => {
    const avgTime = getAverageTime();
    if (avgTime < 200) return { text: '闪电般快速', color: 'text-yellow-500' };
    if (avgTime < 250) return { text: '非常快', color: 'text-green-500' };
    if (avgTime < 300) return { text: '快速', color: 'text-blue-500' };
    if (avgTime < 350) return { text: '正常', color: 'text-gray-500' };
    if (avgTime < 400) return { text: '较慢', color: 'text-orange-500' };
    return { text: '需要改进', color: 'text-red-500' };
  };

  const calculateConsistency = () => {
    if (reactionTimes.length === 0) return 0;
    const avg = getAverageTime();
    if (avg === 0) return 0; // 防止除以0错误
    const variance = reactionTimes.reduce((sum, time) => sum + Math.pow(time - avg, 2), 0) / reactionTimes.length;
    const standardDeviation = Math.sqrt(variance);
    // 一致性评分：标准差越小，一致性越高
    const consistency = 100 - (standardDeviation / avg) * 100;
    return Math.max(0, Math.min(100, Math.round(consistency))); // 确保在0-100范围内
  };

  const handleComplete = () => {
    const avgTime = getAverageTime();
    const score = getScore();
    const testDuration = Math.round((Date.now() - testStartTime) / 1000);
    
    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'reaction',
      score: score,
      completedAt: new Date(),
      duration: testDuration,
      details: {
        averageReactionTime: avgTime,
        reactionTimes: [...reactionTimes],
        totalRounds: reactionTimes.length,
        bestTime: reactionTimes.length > 0 ? Math.min(...reactionTimes) : 0,
        worstTime: reactionTimes.length > 0 ? Math.max(...reactionTimes) : 0,
        consistency: calculateConsistency(),
        rating: getRating().text,
        // 兼容性字段
        averageTime: avgTime
      }
    };
    onComplete(result);
  };

  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.code === 'Space' && (state === 'waiting' || state === 'react')) {
        e.preventDefault();
        handleReaction();
      }
    };

    // 只在测试状态时添加键盘监听器
    if (state === 'waiting' || state === 'react') {
      document.addEventListener('keydown', handleKeyPress);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [handleReaction, timeoutId, state]);

  if (state === 'complete') {
    const rating = getRating();
    
    return (
      <div className="max-w-2xl mx-auto space-y-6">
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <Target className="w-6 h-6 text-green-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {getAverageTime()}ms
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
              <div className="text-lg">
                最终得分: <span className="font-bold text-primary">{getScore()}</span>
              </div>
            </div>

            <div className="grid grid-cols-3 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{reactionTimes.length > 0 ? Math.min(...reactionTimes) : 0}ms</div>
                <div className="text-sm text-muted-foreground">最快反应</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{reactionTimes.length > 0 ? Math.max(...reactionTimes) : 0}ms</div>
                <div className="text-sm text-muted-foreground">最慢反应</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{calculateConsistency()}%</div>
                <div className="text-sm text-muted-foreground">一致性</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">各轮成绩</h3>
              <div className="grid grid-cols-5 gap-2">
                {reactionTimes.map((time, index) => (
                  <div key={index} className="text-center p-2 bg-muted rounded">
                    <div className="font-semibold">{time}ms</div>
                    <div className="text-xs text-muted-foreground">第{index + 1}轮</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-blue-500 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
              >
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {/* Progress */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm">进度</span>
            <span className="text-sm">{currentRound}/{totalRounds}</span>
          </div>
          <Progress value={(currentRound / totalRounds) * 100} />
        </CardContent>
      </Card>

      {/* Main Test Area */}
      <Card className="aspect-square">
        <CardContent 
          className="h-full flex flex-col items-center justify-center p-8 cursor-pointer"
          onClick={(e) => {
            if (state === 'waiting' || state === 'react') {
              e.preventDefault();
              handleReaction();
            }
          }}
        >
          {state === 'ready' && (
            <div className="text-center space-y-6">
              <Zap className="w-16 h-16 text-yellow-500 mx-auto" />
              <div>
                <h2 className="text-2xl font-bold mb-2">准备好了吗？</h2>
                <p className="text-muted-foreground mb-4">
                  等待绿色屏幕出现时，立即点击或按空格键
                </p>
                <Badge variant="secondary">
                  第 {currentRound + 1} / {totalRounds} 轮
                </Badge>
              </div>
              <Button 
                size="lg" 
                onClick={(e) => {
                  e.stopPropagation();
                  startRound();
                }}
                className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              >
                <Zap className="w-5 h-5 mr-2" />
                开始测试
              </Button>
            </div>
          )}

          {state === 'waiting' && (
            <div className="text-center space-y-6 pointer-events-none">
              <div className="w-24 h-24 bg-red-500 rounded-full flex items-center justify-center mx-auto">
                <span className="text-4xl font-bold text-white">
                  {countdown > 0 ? countdown : '...'}
                </span>
              </div>
              <div>
                <h2 className="text-2xl font-bold text-red-500 mb-2">等待...</h2>
                <p className="text-muted-foreground">
                  不要点击！等待绿色屏幕出现
                </p>
              </div>
            </div>
          )}

          {state === 'react' && (
            <div className="text-center space-y-6 w-full h-full flex flex-col items-center justify-center bg-green-500 rounded-lg pointer-events-none">
              <div className="text-6xl font-bold text-white">!</div>
              <div>
                <h2 className="text-3xl font-bold text-white mb-2">现在点击！</h2>
                <p className="text-green-100">
                  点击屏幕或按空格键
                </p>
              </div>
            </div>
          )}

          {state === 'too-early' && (
            <div className="text-center space-y-6">
              <div className="w-24 h-24 bg-red-500 rounded-full flex items-center justify-center mx-auto">
                <span className="text-4xl font-bold text-white">✕</span>
              </div>
              <div>
                <h2 className="text-2xl font-bold text-red-500 mb-2">太快了！</h2>
                <p className="text-muted-foreground mb-4">
                  您在绿色屏幕出现前就点击了
                </p>
              </div>
              <Button 
                onClick={(e) => {
                  e.stopPropagation();
                  setState('ready');
                }}
                className="bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 shadow-md hover:shadow-lg transition-all duration-200"
              >
                重试这一轮
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Results So Far */}
      {reactionTimes.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Timer className="w-5 h-5" />
              当前成绩
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-3 gap-4 text-center">
              <div>
                <div className="text-2xl font-bold">{getAverageTime()}ms</div>
                <div className="text-sm text-muted-foreground">平均时间</div>
              </div>
              <div>
                <div className="text-2xl font-bold">{reactionTimes.length > 0 ? Math.min(...reactionTimes) : 0}ms</div>
                <div className="text-sm text-muted-foreground">最快</div>
              </div>
              <div>
                <div className="text-2xl font-bold">{reactionTimes.length}</div>
                <div className="text-sm text-muted-foreground">已完成</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Instructions */}
      <Card>
        <CardContent className="pt-6">
          <h3 className="font-semibold mb-2">测试说明</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• 等待红色屏幕变为绿色</li>
            <li>• 一看到绿色立即点击或按空格键</li>
            <li>• 共进行 {totalRounds} 轮测试</li>
            <li>• 不要在红色屏幕时点击</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}